package org.farrell.EOSCalc;

import android.app.Activity;
import android.content.Intent;
import android.database.Cursor;
import android.os.Bundle;
import android.view.View;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemSelectedListener;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Spinner;
import android.widget.TextView;
import android.widget.Toast;

public class PropCalc extends Activity {
	
	static final String[] CALC_MODES = new String[] {
		"Fixed T and P",
		"Fixed T at Psat",
		"Fixed P at Tsat"
	};
	
	static final String[] CALC_MODELS = new String[] {
		"Peng-Robinson",
		"Soave-Redlich-Kwong"
	};
	
	private int calcMode=0;
    private int calcModel=0;
    
    private double acentric;
    private double critP;
    private double critT;
	
	private TextView mCompNameText;
	private EditText mPressureText;
    private EditText mTemperatureText;
    
    private Long mRowId;
    
    private CompDbAdapter mDbHelper;
    
    public class ModeItemSelectedListener implements OnItemSelectedListener {

        public void onItemSelected(AdapterView<?> parent, View view, int pos, long id) {
          calcMode = (int) id;
        }

        public void onNothingSelected(AdapterView<?> parent) {
          // Do nothing.
        }
    }
    
    public class ModelItemSelectedListener implements OnItemSelectedListener {

        public void onItemSelected(AdapterView<?> parent, View view, int pos, long id) {
          calcModel = (int) id;
        }

        public void onNothingSelected(AdapterView<?> parent) {
          // Do nothing.
        }
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        
        mDbHelper = new CompDbAdapter(this);
        mDbHelper.open();
        
        setContentView(R.layout.prop_calc);
        setTitle(R.string.prop_calc);

        mCompNameText = (TextView) findViewById(R.id.prop_name);
        mPressureText = (EditText) findViewById(R.id.prop_pres);
        mTemperatureText = (EditText) findViewById(R.id.prop_temp);
        Spinner mModeSpinner = (Spinner) findViewById(R.id.mode);
        Spinner mModelSpinner = (Spinner) findViewById(R.id.model);
        
        ArrayAdapter<String> modeAdapter = new ArrayAdapter<String>(this, android.R.layout.simple_spinner_item, CALC_MODES);
        modeAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
        mModeSpinner.setAdapter(modeAdapter);
        mModeSpinner.setOnItemSelectedListener(new ModeItemSelectedListener());
        
        ArrayAdapter<String> modelAdapter = new ArrayAdapter<String>(this, android.R.layout.simple_spinner_item, CALC_MODELS);
        modelAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
        mModelSpinner.setAdapter(modelAdapter);
        mModelSpinner.setOnItemSelectedListener(new ModelItemSelectedListener());

        Button confirmButton = (Button) findViewById(R.id.button1);

        mRowId = (savedInstanceState == null) ? null :
            (Long) savedInstanceState.getSerializable(CompDbAdapter.KEY_ROWID);
        if (mRowId == null) {
            Bundle extras = getIntent().getExtras();
            mRowId = extras != null ? extras.getLong(CompDbAdapter.KEY_ROWID)
                                    : null;
        }
        
        populateFields();

        confirmButton.setOnClickListener(new View.OnClickListener() {

            public void onClick(View view) {
            	Bundle result;
            	try {
            		result = calculateProperties();
                    
                    Intent i = new Intent(PropCalc.this, PropDisplay.class);
                    i.putExtras(result);
                    startActivity(i);
            	}
            	catch (VLEException v) {
            		String msg = v.getMessage();
            		Toast.makeText(getApplicationContext(), msg, Toast.LENGTH_LONG).show();
            	}
            }

        });
    }
    
    private Bundle calculateProperties() throws VLEException {
    	Compound compound;
    	Bundle result;
    	double Temperature, Pressure;
    	switch (calcModel){
    	case 0: compound = new PREOS(critT, critP, acentric); break;
		case 1: compound = new SRKEOS(critT, critP, acentric); break;
		default: compound = new PREOS(critT, critP, acentric); break;
    	}
    	switch (calcMode){
    	case 0:
    		try {
    			Pressure = Double.parseDouble(mPressureText.getText().toString())*1000;
    			Temperature = Double.parseDouble(mTemperatureText.getText().toString());
    		}
    		catch (Exception e){
    			VLEException err = new VLEException();
    			err.putMessage("Must Enter Temperature and Pressure (numbers only)");
    			throw err;
    		}
    		result = compound.setState(Temperature, Pressure); 
    		break;
    	case 1:
    		try {
    			Temperature = Double.parseDouble(mTemperatureText.getText().toString());
    		}
    		catch (Exception e){
    			VLEException err = new VLEException();
    			err.putMessage("Must Enter Temperature (numbers only)");
    			throw err;
    		}
    		double P = compound.getPsat(Temperature);
    		result = compound.setState(Temperature, P);
    		break;
    	case 2:
    		try {
    			Pressure = Double.parseDouble(mPressureText.getText().toString())*1000;
    		}
    		catch (Exception e){
    			VLEException err = new VLEException();
    			err.putMessage("Must Enter Pressure (numbers only)");
    			throw err;
    		}
    		double T = compound.getTsat(Pressure);
    		result = compound.setState(T, Pressure);
    		break;
    	default:
    		try {
    			Pressure = Double.parseDouble(mPressureText.getText().toString())*1000;
    			Temperature = Double.parseDouble(mTemperatureText.getText().toString());
    		}
    		catch (Exception e){
    			VLEException err = new VLEException();
    			err.putMessage("Must Enter Temperature and Pressure (numbers only)");
    			throw err;
    		}
    		result = compound.setState(Temperature, Pressure);
    	}
    	return result;
    }
    
    
    private void populateFields() {
    	if (mRowId != null) {
            Cursor compound = mDbHelper.fetchComp(mRowId);
            startManagingCursor(compound);
            mCompNameText.setText(compound.getString(
                        compound.getColumnIndexOrThrow(CompDbAdapter.KEY_NAME)));
            critP = compound.getDouble(compound.getColumnIndexOrThrow(CompDbAdapter.KEY_CRIT_PRES));
            critT = compound.getDouble(compound.getColumnIndexOrThrow(CompDbAdapter.KEY_CRIT_TEMP));
            acentric = compound.getDouble(compound.getColumnIndexOrThrow(CompDbAdapter.KEY_ACENTRIC));
        }
    }
    
    @Override
    protected void onResume() {
        super.onResume();
        populateFields();
    }

}
